import random
import os

def load_leaderboard(filename="leaderboard.txt"):
    scores = []
    if os.path.exists(filename):
        with open(filename, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                parts = line.split(",", 1)
                if len(parts) != 2:
                    continue
                name = parts[0].strip()
                try:
                    attempts = int(parts[1])
                except:
                    continue
                scores.append((name, attempts))
    return scores

def save_leaderboard(scores, filename="leaderboard.txt"):
    scores_sorted = sorted(scores, key=lambda x: x[1])
    with open(filename, "w", encoding="utf-8") as f:
        for name, attempts in scores_sorted:
            f.write(f"{name},{attempts}\n")

def main():
    print("欢迎来到猜数字游戏！")
    print("我已经选择了一个1到100之间的数字。你有无限次机会猜测它。\n")
    number = random.randint(1, 100)
    attempts = 0

    while True:
        guess_str = input("请输入你猜的数字 (1-100): ")
        guess_str = guess_str.strip()
        if not guess_str.isdigit():
            print("请输入有效的数字。")
            continue
        guess = int(guess_str)
        if guess < 1 or guess > 100:
            print("请输入 1 到 100 之间的数字。")
            continue
        attempts += 1
        if guess < number:
            print("太小了，请再试一次。")
        elif guess > number:
            print("太大了，请再试一次。")
        else:
            print(f"恭喜你猜对了！这个数字确实是 {number}。")
            print(f"你总共猜了 {attempts} 次。\n")
            name = input("请输入你的名字，用于排行榜记录: ").strip()
            if not name:
                name = "匿名"
            scores = load_leaderboard()
            scores.append((name, attempts))
            save_leaderboard(scores)
            print("\n当前排行榜 (猜测次数越少排名越靠前):")
            scores_sorted = sorted(scores, key=lambda x: x[1])
            for i, (n, a) in enumerate(scores_sorted[:5], start=1):
                print(f"{i}. {n} —— {a} 次")
            break

if __name__ == "__main__":
    main()